import { CustomError, CustomErrorType } from '../customError';
import { reportError } from '../actions/error';

function errorMiddleware({ dispatch }) {
  return next => (action) => {
    if (!action.error) {
      return next(action);
    }
    
    const error = action.payload;
    if (error instanceof CustomError) {
      let title = '异常';
      const lines = [];
      
      switch (error.type) {
        case CustomErrorType.HTTP:
          title = '网络异常';
          lines.push('请检查网络连接');
          lines.push(`状态码: ${error.data.code}`);
          lines.push(`状态信息: ${error.message}`);
          break;
        
        case CustomErrorType.SERVICE:
          title = '服务异常';
          lines.push(`访问 ${error.data.url} 出错`);
          lines.push('请刷新页面重试');
          lines.push(`返回码: ${error.data.code}`);
          lines.push(`返回信息: ${error.message}`);
          break;
        
        case CustomErrorType.APP:
          title = '系统异常';
          break;
        
        default:
          break;
      }
      
      dispatch(reportError({
        title,
        type: error.type,
        messages: lines
      }));
    } else if (error instanceof Error) {
      if (errorMiddleware.isConsole) {
        console.error(error);
      }
      dispatch(reportError({
        title: '异常',
        messages: [error.message]
      }));
    }
    
    return next(action);
  };
}

errorMiddleware.isConsole = false;

export default errorMiddleware;
